import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useContractStore = defineStore('contract', () => {
  // 合同列表（已生效合同）
  const contracts = ref([
    {
      id: 5961,
      title: '江西制药厂房租赁合同',
      number: '428270307199',
      name: '江西制药有限公司',
      type: '租赁合同',
      date: '2023-08-19',
      contractEndDate: '2025-06-12',
      status: '已通过',
      applyDate:'2025-03-10',
      partyBAddress: '默认乙方地址',
      applicant: '张三'
    }
  ])
  
  // 待审批合同列表
  const pendingApprovals = ref([
  {
      id: 5962,
      title: '辽宁造船服务合同',
      number: '428274719713',
      name: '辽宁造船有限公司',
      type: '租赁合同',
      date: '2022-06-30',
      contractEndDate: '2025-01-20',
      status: '待审批',
      applyDate:'2022-05-01',
      partyBAddress:'西城区大街',
      applicant: '王五'
  }
])
  
  // 添加合同到待审批列表
  const addPendingApproval = (newContract) => {
    pendingApprovals.value.unshift({
      ...newContract,
      id: newContract.id || Date.now(),
      status: '待审批',
      applyDate: newContract.applyDate || new Date().toISOString().split('T')[0]
    })
  }
  
  // 添加新合同（从List页面调用）
  const addContract = (newContract) => {
    contracts.value.unshift(newContract)
  }
  
  // 更新合同（从List页面调用）
  const updateContract = (updatedContract) => {
    const index = contracts.value.findIndex(c => c.id === updatedContract.id)
    if (index !== -1) {
      contracts.value.splice(index, 1, updatedContract)
    }
  }
  
  // 审批通过，将合同从待审批移到正式合同列表
const approveContract = (contractId) => {
  const pendingIndex = pendingApprovals.value.findIndex(c => c.id === contractId)
  if (pendingIndex !== -1) {
    const approvedContract = {
      ...pendingApprovals.value[pendingIndex],
      status: '已通过',
      approveDate: new Date().toISOString().split('T')[0]
    }
    
    // 添加到正式合同列表
    contracts.value.unshift(approvedContract)
    // 从待审批列表移除
    pendingApprovals.value.splice(pendingIndex, 1)
  }
}
  
// 审批拒绝
const rejectContract = (contractId, reason) => {
  const pendingIndex = pendingApprovals.value.findIndex(c => c.id === contractId)
  if (pendingIndex !== -1) {
    const rejectedContract = {
      ...pendingApprovals.value[pendingIndex],
      status: '已拒绝',
      rejectReason: reason,
      approveDate: new Date().toISOString().split('T')[0]
    }
    
    // 添加到正式合同列表
    contracts.value.unshift(rejectedContract)
    // 从待审批列表移除
    pendingApprovals.value.splice(pendingIndex, 1)
  }
}

const removeContract = (id) => {
  contracts.value = contracts.value.filter(c => c.id !== id)
  pendingApprovals.value = pendingApprovals.value.filter(c => c.id !== id)
}
 
  return { 
    contracts, 
    pendingApprovals, 
    removeContract,
    addContract,
    updateContract,
    addPendingApproval,
    approveContract,
    rejectContract
  }
})  